import { Fragment } from 'react'
import { Form } from 'antd-mobile'
import Input from './FormItems/Input'
import Textarea from './FormItems/TextArea'
import './index.less'
import type {
  FormListType,
  FormListItemType,
  FormItemPropsType,
  InputPropsType,
  TextAreaPropsType,
} from '@/form'

type PropsType = {
  formList: FormListType
  footer: React.ReactNode,
  onSubmit: (values: any) => void,
  onReset?: () => void
}
const FormItem = Form.Item

const FormList = (props: PropsType) => {

  const [form] = Form.useForm()
  const {
    formList,
    footer,
    onSubmit,
    onReset,
  } = props

  /**
   * 表单控件
   * keys: 'input' | 'textarea'
   */
  const formItemsMap = {
    input: ({
      label,
      name,
      formItemProps = {},
      formFieldProps = {},
    }: {
      label: string,
      name: string,
      formItemProps?: FormItemPropsType,
      formFieldProps?: InputPropsType,
      }, index: number): React.ReactNode => {
      const { rules, tooltip, intro, ...formItemOhterProps } = formItemProps
      const { maxLength, rows, autoSize, placeholder, ...formFieldOhterProps } = formFieldProps
      return <Fragment key={`${name}-${index}`}>
        <FormItem
          label={label}
          // tooltip={tooltip}
          // intro={intro}
          rules={rules}
          name={name}
          {...formItemOhterProps}
        >
          <Input
            label={label}
            name={name}
            maxLength={maxLength}
            rows={rows}
            autoSize={autoSize}
            placeholder={placeholder}
            {...formFieldOhterProps}
          />
        </FormItem>
      </Fragment>
    },
    textarea: ({
      label,
      name,
      formItemProps = {},
      formFieldProps = {}
    }: {
      label: string,
      name: string,
      formItemProps?: FormItemPropsType,
      formFieldProps?: TextAreaPropsType,
    }, index: number): React.ReactNode => {
      const { rules, tooltip, intro, ...formItemOhterProps } = formItemProps
      const { maxLength, rows, autoSize, placeholder, showCount, ...formFieldOhterProps } = formFieldProps
      return <Fragment key={`${name}-${index}`}>
        <FormItem
          label={label}
          rules={rules}
          name={name}
          {...formItemOhterProps}
        >
          <Textarea
            name={name}
            label={label}
            maxLength={maxLength}
            rows={rows}
            autoSize={autoSize}
            placeholder={placeholder}
            showCount={showCount}
            {...formFieldOhterProps}
          />
        </FormItem>
      </Fragment>
    }
  }

  return <Form
    form={form}
    onFinish={onSubmit}
    layout='horizontal'
    footer={footer}
  >
    {formList.map((item: FormListItemType, index: number) => {
      return formItemsMap[item.type](item, index)
    })}
  </Form>
}

export default FormList
